import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userInfo, userPermission, userMessage } from '@/types'
import { getUserInfo, getUserPermission } from '@/api/user'

// 用户模块 token setToken removeToken
export const useUserStore = defineStore(
  'Myuser',
  () => {
    const token = ref('')
    // 用户权限
    const userPermission = ref(new Array<userPermission>())
    // 用户信息
    const user = ref(new userInfo())
    //用户消息
    const userMessage = ref(new Array<userMessage>())

    // 设置token
    const setToken = (newToken: string) => {
      token.value = newToken
    }
    // 移除token
    const removeToken = () => {
      token.value = ''
    }
    // 设置用户权限
    const setUserPermission = async () => {
      const res = await getUserPermission()
      userPermission.value = res.data
    }
    // 设置用户信息
    const setUserInformation = async () => {
      const res = await getUserInfo()
      user.value = res.data
    }
    // 设置用户
    const setUser = (obj: userInfo) => {
      user.value = obj
    }
    //设置用户消息
    const setUserMessage = (obj: userMessage) => {
      userMessage.value.push(obj)
    }
    //清空全部消息
    const clearUserMessage = () => {
      userMessage.value = new Array<userMessage>()
    }
    return {
      token,
      user,
      userPermission,
      userMessage,
      setToken,
      removeToken,
      setUserInformation,
      setUserPermission,
      setUser,
      setUserMessage,
      clearUserMessage
    }
  },
  {
    persist: true
  }
)
